﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinDocker.Common.Global;
using WinDocker.Common.Helper.WindowsService;
using System.Reflection.Emit;
using System.Xml.Linq;
using WinDocker.UC;
using System.Collections;

namespace WinDocker
{
    public partial class Form1 : Form
    {
        private const string WIN_SERVER_NAME = "WinDockerService";


        private UC.ModuleUC ModuleUCObj = null;

        private Panel panelWithScroll = null;

        private void ModuleUCShowDeal()
        {
            try
            {
                if (this.ModuleUCObj == null)
                {
                    // 创建一个panel，并设置AutoScroll属性为true
                    this.panelWithScroll = new Panel
                    {
                        //Dock = DockStyle.Fill,
                        AutoScroll = true,
                        Parent = this,
                        BorderStyle = BorderStyle.FixedSingle
                    };
                    this.ModuleUCObj = new UC.ModuleUC();
                    this.ModuleUCObj.Parent = this.panelWithScroll;
                    this.ModuleUCObj.Location = new Point(0, 0);
                }
                this.ModuleUCObj.ChkCheckedShow();
                this.panelWithScroll.Width = this.ModuleUCObj.Width + 20;
                var uc = this.panelWithScroll;//this.ModuleUCObj;
                var obLoc = this.pnlService;
                uc.Location = new Point(obLoc.Location.X + obLoc.Width + 3, obLoc.Location.Y - 5);
                uc.Show();
                uc.BringToFront();
                uc.Visible = this.btnStop.Enabled;
                uc.Height = this.ClientSize.Height - uc.Location.Y - 10;
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", $"Form1 ModuleUCShowDeal Err:{ex.Message}");
            }
        }

        public Form1()
        {
            InitializeComponent();
        }

        private bool JudgeProgramIsOpen(out string msg)
        {
            msg = "";
            try
            {
                var testSerName = "W32Time";//时间服务
                var b = ReStartServer.JudgeService(testSerName);
                if (!b)
                {
                    msg = "操作系统的wmic service命令无法使用,请先检查与设置!";
                    return b;
                }
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", $"Form1 JudgeProgramIsOpen Err:{ex.Message}");
            }
            return true;
        }

        private string GetServiceInstallPath(string serviceName)
        {
            try
            {
                string registryPath = $@"SYSTEM\CurrentControlSet\Services\{serviceName}";
                using (Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(registryPath))
                {
                    if (key != null)
                    {
                        Object obj = key.GetValue("ImagePath");
                        if (obj != null)
                        {
                            return obj.ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", $"Form1 GetServiceInstallPath Err:{ex.Message}");
            }
            return "";//"Service not found or path not available";
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (!this.JudgeProgramIsOpen(out var msg))
            {
                MessageBox.Show($"程序无法打开!\r\n【原因】:\r\n{msg}", "提示");
                System.Diagnostics.Process.GetCurrentProcess().Kill();
                return;
            }
            var serPath = this.GetServiceInstallPath(WIN_SERVER_NAME);
            serPath = (serPath ?? "").Trim();
            var serPath2 = AppDomain.CurrentDomain.BaseDirectory + @"Service\WinDocker.Service.exe";
            if ((serPath.IndexOf(serPath2) < 0) && (serPath != ""))
            {
                MessageBox.Show($"服务程序的实际安装路径与当前路径不符!\r\n\r\n({serPath})\r\n", "【超级提示】");
            }
            this.ExistsServiceUIDeal();
            this.ServiceRunUIDeal();
            this.ModuleUCShowDeal();

            try
            {
                //this.label2.ForeColor = Color.White; 
                //this.label2.BackColor = Color.DarkBlue;
                //this.InitializeExeListView();
                /*
                 
                 */
            }
            catch { }
        }

        private void SelectButton_Click(object sender, EventArgs e)
        {
            // 获取选中的第一个exe文件（单选模式下只有一个）
            if (exeListView.SelectedItems.Count > 0)
            {
                var selectedItem = exeListView.SelectedItems[0];
                var exeName = Path.GetFileName(selectedItem.Text);
                this.pnlExe.Tag = exeName;
                var path = $"{selectedItem.Tag}";
                var bAdd = this.SelectButtonJudgeAdd(exeName, out var dirList);
                if (bAdd)
                {
                    this.ProgramInstall(exeName, path, dirList);
                }
                else//更新
                {
                    this.ProgramUpgrade(exeName, path, dirList);
                }
                MessageBox.Show($"选中的EXE文件:{exeName}\r\n\r\n文件路径:{path}\r\n", "选择结果",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.pnlExe.Visible = false;
            }
            else
            {
                MessageBox.Show("请先选择一个EXE文件", "提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void ProgramInstall(string exeName, string sourcePath, List<string> dirList)
        {
            try
            {
                if (MessageBox.Show($"程序部署前,是否检查好了配置及安装了支持环境?", "提示", MessageBoxButtons.OKCancel) != DialogResult.OK)
                {
                    return;
                }
                this.pnlInstall.Visible = true;
                this.pnlInstall.Tag = dirList;
                this.pnlInstall.Location = new Point((this.ClientSize.Width - this.pnlInstall.Width) / 2, (this.ClientSize.Height - this.pnlInstall.Height) / 2);
                this.txtAppName.Tag = sourcePath;
                this.txtAppName.Text = "";
                this.txtAppServicePort.Text = "";
                this.rbAppServicePort.Checked = false;
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", $"Form1 ProgramInstall Err:{ex.Message}");
                MessageBox.Show($"程序部署出错:{ex.Message}");
                this.pnlInstall.Visible = false;
            }
            //finally
            //{
            //    this.pnlInstall.Visible = false;
            //}
        }

        private void ProgramUpgrade(string exeName, string sourcePath, List<string> dirList)
        {
            try
            {
                var cfgModels = this.ModuleUCObj.DevSerCfgUCModels;
                var cfms = cfgModels.Where(p => p.DirPath.IndexOf(exeName) >= 0);
                if (!cfms.Any())
                {
                    MessageBox.Show("配置异常,请检查!", "提示");
                    return;
                }
                this.UpgradeListView.Items.Clear();
                foreach (var cfm in cfms)
                {
                    this.UpgradeListView.Items.Add(new ListViewItem(cfm.DevSerName)
                    {
                        Tag = cfm
                    });
                }
                this.pnlUpgrade.Tag = sourcePath;
                this.pnlInstall.Tag = dirList;
                this.pnlUpgrade.Visible = true;
                //var obLog = new
                //{
                //    exeName,
                //    sourcePath,
                //    dirList,
                //    cfgModels
                //};
                //LogWrite.TxtExport_DateNow("LogTest.txt", $"\r\n{Tool.ConvertJsonString(Newtonsoft.Json.JsonConvert.SerializeObject(obLog))}\r\n");
                /*                 
{
    "exeName": "Consumables.Example.exe",
    "sourcePath": "F:\\Test\\net6.0-windows7.0\\Service\\Consumables.Example.exe",
    "dirList": [
        "F:\\Test\\net6.0-windows7.0\\Service\\Deploy\\KnDService\\JtDFSer_Consumables.Example.exe_0",
        "F:\\Test\\net6.0-windows7.0\\Service\\Deploy\\KnDService\\JtDFSer_Consumables.Example.exe_1",
        "F:\\Test\\net6.0-windows7.0\\Service\\Deploy\\KnDService\\JtDFSer_Consumables.Example.exe_2",
        "F:\\Test\\net6.0-windows7.0\\Service\\Deploy\\KnDService\\JtDFSer_Consumables.Example.exe_3"
    ],
    "cfgModels": [
        {
            "DirPath": "Service\\Deploy\\KnDService\\JtDFSer_Consumables.Example.exe_0",
            "DevSerName": "测试1",
            "CfgFileName": "Consumables.Example.dll.config",
            "EnableFieldName": "IsEnable"
        },
        {
            "DirPath": "Service\\Deploy\\KnDService\\JtDFSer_Consumables.Example.exe_1",
            "DevSerName": "测试2",
            "CfgFileName": "Consumables.Example.dll.config",
            "EnableFieldName": "IsEnable"
        },
        {
            "DirPath": "Service\\Deploy\\KnDService\\JtDFSer_Consumables.Example.exe_2",
            "DevSerName": "小d测试3",
            "CfgFileName": "Consumables.Example.dll.config",
            "EnableFieldName": "IsEnable"
        },
        {
            "DirPath": "Service\\Deploy\\KnDService\\JtDFSer_Consumables.Example.exe_3",
            "DevSerName": "小d测试4",
            "CfgFileName": "Consumables.Example.dll.config",
            "EnableFieldName": "IsEnable"
        }
    ]
}                 
                 */
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", $"Form1 ProgramUpgrade Err:{ex.Message}");
            }
        }

        private bool SelectButtonJudgeAdd(string exeName, out List<string> dirList)
        {
            var bAdd = true;
            dirList = new List<string>();
            try
            {
                var dirPath = AppDomain.CurrentDomain.BaseDirectory + @"Service\Deploy\KnDService";
                var directories = new List<string>();
                var dirs = Directory.GetDirectories(dirPath);
                if (dirs.Any())
                {
                    dirList.AddRange(dirs);
                }
                foreach (string dir in dirs)
                {
                    // 获取目录的名称
                    string dirName = Path.GetFileName(dir);
                    directories.Add(dirName);
                }
                //JtDFSer_Consumables.Example.exe_0
                foreach (var str in directories)
                {
                    var sArray = str.Split('_');
                    if (sArray.Length <= 1)
                    {
                        continue;
                    }
                    var str2 = sArray[1];
                    if (exeName == str2)
                    {
                        bAdd = false;
                        continue;
                    }
                }
                //bAdd = (!directories.Any(p => p.IndexOf(exeName) >= 0));
                //var json = Tool.ConvertJsonString(Newtonsoft.Json.JsonConvert.SerializeObject(directories));
                //MessageBox.Show(json);
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", $"Form1 SelectButtonJudgeAdd Err:{ex.Message}");
            }
            return bAdd;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (!this.IsExistsService)
            {
                MessageBox.Show("服务不存在,无法继续操作!");
                return;
            }
            if (this.IsExistsServiceRun)
            {
                MessageBox.Show("服务已启动运行!");
                return;
            }
            this.ModuleUCObj.SetAllDevSerRun(true);
            var str = ReStartServer.StartService(WIN_SERVER_NAME);
            MessageBox.Show("服务启动操作结束，" + str);

            this.ServiceRunUIDeal();

        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (!this.IsExistsService)
            {
                MessageBox.Show("服务不存在,无法继续操作!");
                return;
            }
            if (!this.IsExistsServiceRun)
            {
                MessageBox.Show("服务已停止运行!");
                return;
            }
            this.ModuleUCObj.SetAllDevSerRun(false);
            var str = ReStartServer.StopService(WIN_SERVER_NAME);
            this.ModuleUCObj.SetAllDevSerRun();
            MessageBox.Show("服务停止操作结束，" + str);
            this.ServiceRunUIDeal();
        }

        private void btnSetup_Click(object sender, EventArgs e)
        {
            if (this.IsExistsService)
            {
                MessageBox.Show("服务已存在,无法安装!", "提示");
                return;
            }
            var serPath = AppDomain.CurrentDomain.BaseDirectory + @"Service\WinDocker.Service.exe";
            if (!File.Exists(serPath))
            {
                MessageBox.Show($"服务程序文件不存在!\r\n{serPath}", "提示");
                return;
            }
            var str = ReStartServer.SetupService(serPath, WIN_SERVER_NAME);
            MessageBox.Show("服务安装操作结束，" + str);
            this.ExistsServiceUIDeal();
            this.ServiceRunUIDeal();
        }

        private void btnUninstall_Click(object sender, EventArgs e)
        {
            if (!this.IsExistsService)
            {
                MessageBox.Show("服务不存在,无法继续操作!");
                return;
            }
            if (this.IsExistsServiceRun)
            {
                this.btnStop_Click(null, null);
            }
            string str = ReStartServer.UnSetupService(WIN_SERVER_NAME);
            MessageBox.Show("服务卸载操作结束，" + str);
            this.ExistsServiceUIDeal();
            this.ServiceRunUIDeal();
        }

        /// <summary>
        /// 后台服务状态(启动、停止等)界面联动处理
        /// </summary>
        private void ServiceRunUIDeal()
        {
            try
            {
                if (!this.IsExistsService)
                {
                    this.btnStart.Enabled = false;
                    this.btnStop.Enabled = false;
                    return;
                }
                var isExistsServiceRun = this.IsExistsServiceRun;
                this.btnStart.Enabled = !isExistsServiceRun;
                this.btnStop.Enabled = isExistsServiceRun;
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", "Form1 ServiceRunUIDeal Err:" + ex.Message);
            }
        }


        /// <summary>
        /// 服务是否存在
        /// </summary>
        private bool IsExistsService
        {
            get
            {
                return ReStartServer.JudgeService(WIN_SERVER_NAME);
            }
        }

        /// <summary>
        /// 服务是否运行 
        /// </summary>
        private bool IsExistsServiceRun
        {
            get
            {
                return ReStartServer.JudgeServiceRun(WIN_SERVER_NAME);
            }
        }

        /// <summary>
        /// 后台服务存在与否界面联动处理
        /// </summary>
        private void ExistsServiceUIDeal()
        {
            try
            {
                bool isExistsService = this.IsExistsService;
                this.btnSetup.Enabled = !isExistsService;
                this.btnUninstall.Enabled = isExistsService;
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", "Form1 ExistsServiceUIDeal Err:" + ex.Message);
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (MessageBox.Show("是否要退出本程序？", "退出程序", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    //this.mainNotifyIcon.Visible = false; 
                    System.Diagnostics.Process.GetCurrentProcess().Kill();
                }
                else
                {
                    e.Cancel = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("FormClosing Err:" + ex.Message);
            }
        }

        private void btnSetup_EnabledChanged(object sender, EventArgs e)
        {
            try
            {
                var btn = (Control)sender;

            }
            catch (Exception ex)
            {
                MessageBox.Show("btnSetup_EnabledChanged Err:" + ex.Message);
            }
        }

        private void btnStop_EnabledChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.panelWithScroll == null)
                {
                    return;
                }
                var btn = (Control)sender;
                this.panelWithScroll.Visible = btn.Enabled;
            }
            catch (Exception ex)
            {
                MessageBox.Show("btnSetup_EnabledChanged Err:" + ex.Message);
            }
        }

        private void panel1_DragEnter(object sender, DragEventArgs e)
        {
            // 验证拖拽内容是否为文件夹
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                if (Directory.Exists(files[0]))
                {
                    e.Effect = DragDropEffects.Copy;
                    return;
                }
            }
            e.Effect = DragDropEffects.None;
        }

        private void panel1_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] folders = (string[])e.Data.GetData(DataFormats.FileDrop);

                if (folders.Length > 0 && Directory.Exists(folders[0]))
                {
                    string folderPath = folders[0];

                    // 获取所有exe文件（不包括子文件夹）
                    var exeFiles = Directory.GetFiles(folderPath, "*.exe")
                        .Select(path => new FileInfo(path))
                        .Where(f => (f.Attributes & FileAttributes.Directory) != FileAttributes.Directory)
                        .ToList();

                    // 清空并填充ListView
                    exeListView.Items.Clear();

                    foreach (var exe in exeFiles)
                    {
                        exeListView.Items.Add(new ListViewItem(exe.Name)
                        {
                            Tag = exe.FullName // 存储完整路径
                        });
                    }

                    // 显示控件
                    //exeListView.Visible = exeFiles.Count > 0;
                    //selectButton.Visible = exeFiles.Count > 0;
                    this.pnlExe.Visible = exeFiles.Count > 0;
                    if (this.pnlExe.Visible)
                    {
                        this.pnlExe.Location = new Point((this.ClientSize.Width - this.pnlExe.Width) / 2, (this.ClientSize.Height - this.pnlExe.Height) / 2);
                    }

                    if (exeFiles.Count == 0)
                    {
                        MessageBox.Show($"该文件夹中没有找到EXE文件,无法进行发布或更新\r\n[注:即使没有更新Exe文件也要提供Exe文件]", "信息",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
        }

        private void UpgradeButton_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取选中的第一个程序文件（单选模式下只有一个）
                if (UpgradeListView.SelectedItems.Count > 0)
                {
                    //"sourcePath": "F:\\Test\\net6.0-windows7.0\\Service\\Consumables.Example.exe"
                    // this.pnlUpgrade.Tag = sourcePath;
                    var sourcePath = "";
                    if (this.pnlUpgrade.Tag is string)
                    {
                        sourcePath = (this.pnlUpgrade.Tag as string);
                    }
                    sourcePath = (sourcePath ?? "").Trim();
                    if (sourcePath == "")
                    {
                        MessageBox.Show("所拖进的升级程序文件夹不存在!", "提示");
                        this.pnlUpgrade.Visible = false;
                        return;
                    }
                    sourcePath = Path.GetDirectoryName(sourcePath);
                    var selectedItem = UpgradeListView.SelectedItems[0];
                    var devSerName = Path.GetFileName(selectedItem.Text);
                    var cfm = (selectedItem.Tag as DevSerCfgUCModel);
                    var mu = this.ModuleUCObj;
                    DevSerCfgUC uc = null;
                    foreach (var ct in mu.Controls)
                    {
                        if (!(ct is DevSerCfgUC))
                        {
                            continue;
                        }
                        var _uc = (ct as DevSerCfgUC);
                        if (_uc.DevSerCfgUCModelObj.DirPath == cfm.DirPath)
                        {
                            uc = _uc;
                            break;
                        }
                    }
                    if (uc == null)
                    {
                        MessageBox.Show("对应的部署程序不存在!", "提示");
                        this.pnlUpgrade.Visible = false;
                        return;
                    }
                    var bRun = uc.DevSerIsRun;
                    if (bRun)
                    {
                        uc.SetDevSerRunBySingle(!bRun);
                    }

                    var dirPath = AppDomain.CurrentDomain.BaseDirectory + cfm.DirPath;

                    Tool.CopyDirectory(sourcePath, dirPath, true);

                    if (bRun)
                    {
                        uc.SetDevSerRunBySingle(bRun);
                    }
                    //var json = Tool.ConvertJsonString(Newtonsoft.Json.JsonConvert.SerializeObject(cfm));
                    MessageBox.Show($"对选中的程序:{devSerName}\r\n\r\n进行升级处理结束!\r\n", "操作结果",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.pnlUpgrade.Visible = false;
                }
                else
                {
                    MessageBox.Show("请先选择一个要升级的程序文件", "提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                this.pnlUpgrade.Visible = false;
                MessageBox.Show($"Err:{ex.Message}");
            }
            //finally
            //{
            //    this.pnlUpgrade.Visible = false;
            //}
        }

        private void pnlExe_VisibleChanged(object sender, EventArgs e)
        {
            try
            {
                var ct = (Control)sender;
                if (ct.Visible)
                {
                    ct.BringToFront();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"VisibleChanged Err:{ex.Message}");
            }
        }

        private void SetupLkb_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                var sourcePath = "";
                if (this.pnlUpgrade.Tag is string)
                {
                    sourcePath = (this.pnlUpgrade.Tag as string);
                }
                sourcePath = (sourcePath ?? "").Trim();
                if (sourcePath == "")
                {
                    MessageBox.Show("所拖进的升级程序文件夹不存在!", "提示");
                    return;
                }

                List<string> dirList = null;
                if (this.pnlInstall.Tag is List<string>)
                {
                    dirList = (this.pnlInstall.Tag as List<string>);
                }
                if (dirList == null)
                {
                    MessageBox.Show("部署程序文件夹为空!", "提示");
                    return;
                }
                var exeName = "";
                if (this.pnlExe.Tag is string)
                {
                    exeName = (this.pnlExe.Tag as string);
                }
                exeName = (exeName ?? "").Trim();
                if (exeName == "")
                {
                    MessageBox.Show("程序文件名不能为空!", "提示");
                    return;
                }
                this.ProgramInstall(exeName, sourcePath, dirList);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Err:{ex.Message}");
            }
            finally
            {
                this.pnlUpgrade.Visible = false;
            }
        }

        private void label1_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                /*
                var lt = Tool.GetListeningPorts().Where(p => p.Protocol.ToLower().Trim() == "tcp").GroupBy(k => k.PortNumber).Select(w => w.First());
                var json = Tool.ConvertJsonString(Newtonsoft.Json.JsonConvert.SerializeObject(lt));
                LogWrite.TxtExport_DateNow("LogTest.txt", json);
                MessageBox.Show("ok");
                */

            }
            catch (Exception ex)
            {
                MessageBox.Show($"Err:{ex.Message}");
            }
        }

        private void btnAppInstall_Click(object sender, EventArgs e)
        {
            try
            {
                var sourcePath = "";
                if (this.txtAppName.Tag is string)
                {
                    sourcePath = (this.txtAppName.Tag as string);
                }
                sourcePath = (sourcePath ?? "").Trim();
                if (sourcePath == "")
                {
                    MessageBox.Show("所拖进的升级程序文件夹不存在!", "提示");
                    return;
                }
                sourcePath = Path.GetDirectoryName(sourcePath);

                List<string> dirList = null;
                if (this.pnlInstall.Tag is List<string>)
                {
                    dirList = (this.pnlInstall.Tag as List<string>);
                }
                if (dirList == null)
                {
                    MessageBox.Show("部署程序文件夹为空!", "提示");
                    return;
                }
                var exeName = "";
                if (this.pnlExe.Tag is string)
                {
                    exeName = (this.pnlExe.Tag as string);
                }
                exeName = (exeName ?? "").Trim();
                if (exeName == "")
                {
                    MessageBox.Show("程序文件名不能为空!", "提示");
                    return;
                }

                var appName = (this.txtAppName.Text ?? "").Trim();
                if (appName == "")
                {
                    MessageBox.Show($"程序名称不能为空!", "提示");
                    return;
                }
                var port = 0;
                if (this.rbAppServicePort.Checked)
                {
                    var sPort = (this.txtAppServicePort.Text ?? "").Trim();
                    if (sPort == "")
                    {
                        var ltPort = Tool.GetListeningPorts().Where(p => p.Protocol.ToLower().Trim() == "tcp").GroupBy(k => k.PortNumber).Select(w => w.First()).Select(o => o.PortNumber).ToList();
                        foreach (string dir in dirList)
                        {
                            // 获取目录的名称 JtDFSer_Consumables.Example.exe_1
                            var dirName = Path.GetFileName(dir);
                            var dnArray = dirName.Split('_');
                            if (dnArray.Length <= 2)
                            {
                                continue;
                            }
                            var _sPort = dnArray[2];
                            if (!int.TryParse(_sPort, out var _iPort))
                            {
                                continue;
                            }
                            if (_iPort <= 0)
                            {
                                continue;
                            }
                            if (!ltPort.Contains(_iPort))
                            {
                                ltPort.Add(_iPort);
                            }
                        }
                        if (ltPort.Any())
                        {
                            port = ltPort.Max() + 1;
                        }
                        else
                        {
                            port = 80;
                        }
                        this.txtAppServicePort.Text = port.ToString();
                    }
                    else
                    {
                        if (!uint.TryParse(sPort, out var i))
                        {
                            MessageBox.Show($"服务端口非正整数!", "提示");
                            return;
                        }
                        port = (int)i;
                    }
                }
                else
                {
                    var ltPort = new List<int>();
                    foreach (string dir in dirList)
                    {
                        // 获取目录的名称 JtDFSer_Consumables.Example.exe_1
                        var dirName = Path.GetFileName(dir);
                        var dnArray = dirName.Split('_');
                        if (dnArray.Length <= 2)
                        {
                            continue;
                        }
                        var _sPort = dnArray[2];
                        if (!int.TryParse(_sPort, out var _iPort))
                        {
                            continue;
                        }
                        if (_iPort >= 0)
                        {
                            continue;
                        }
                        if (!ltPort.Contains(_iPort))
                        {
                            ltPort.Add(_iPort);
                        }
                    }

                    if (ltPort.Any())
                    {
                        port = ltPort.Min() - 1;
                    }
                    else
                    {
                        port = -80;
                    }

                    this.txtAppServicePort.Text = port.ToString();
                }
                var cfgDirPath = $@"Service\Deploy\KnDService\JtDFSer_{exeName}_{port}";
                var dirPath = AppDomain.CurrentDomain.BaseDirectory + cfgDirPath;//cfm.DirPath;
                Tool.CopyDirectory(sourcePath, dirPath, true);
                this.ModuleUCObj.DevSerCfgUCModelListInitDeal(cfgDirPath, appName);
                this.ModuleUCObj.ChkCheckedShow();
                MessageBox.Show($"程序部署成功!", "提示");
                this.pnlInstall.Visible = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Err:{ex.Message}");
                this.pnlInstall.Visible = false;
            }
        }

        private void rbAppServicePort_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                var rb = (RadioButton)sender;
                this.pnlAppServicePort.Enabled = rb.Checked;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Err:{ex.Message}");
            }
        }

        private void btnSelectCancel_Click(object sender, EventArgs e)
        {
            try
            {
                var ct = (Control)sender;
                var parentCt = ct.Parent;
                parentCt.Visible = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"ButtonCancel Err:{ex.Message}");
            }
        }
    }
}